package com.itnoob.whitelist.aspect;

import com.itnoob.whitelist.annotation.WhiteList;
import com.itnoob.whitelist.config.WhiteListProperties;
import com.itnoob.whitelist.service.WhiteListService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * WhiteListAspect类
 * @author zhoujun
 * @date 2025/3/20 23:39
 */
@Aspect
public class WhiteListAspect {
    //注入白名单配置类
    private final WhiteListProperties whiteListProperties;
    //注入白名单服务
    private final WhiteListService whiteListService;

    public WhiteListAspect(WhiteListProperties whiteListProperties, WhiteListService whiteListService) {
        this.whiteListProperties = whiteListProperties;
        this.whiteListService = whiteListService;
    }

    @Pointcut("@annotation(com.itnoob.whitelist.annotation.WhiteList)")
    public void pointcut(){}

    //定义前置通知,在切点之前执行
    @Before("pointcut() && @annotation(whiteList)")
    public void before(JoinPoint joinPoint, WhiteList whiteList){
        //获取请求对象
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        String userOrIp = request.getHeader("userOrIp");
        //获取方法上的白名单,来自注解
        String[] value = whiteList.value();
        //获取全局白名单列表
        List<String> global = whiteListProperties.getGlobal();
        //调用白名单服务的校验方法,如果不在白名单中,抛出异常
        whiteListService.check(userOrIp,value,global);
    }
}
